package tree;

import offer.TreeNode;

import java.util.*;

/**
 * 给你一个二叉树，请你返回其按 层序遍历 得到的节点值。 （即逐层地，从左到右访问所有节点）。
 */
public class leetCode102_levelOrder {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(1);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(5);
        root.left.right = new TreeNode(6);
        leetCode102_levelOrder a = new leetCode102_levelOrder();
        a.build(root);
    }
    List<List<Integer>> ans = new ArrayList<>();
    public List<List<Integer>> levelOrder(TreeNode root) {
        if(root == null) return ans;
        build(root);
        return ans;
    }

    public void build(TreeNode root){
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.add(root);
        while (!deque.isEmpty()){
            int size = deque.size();
            List<Integer> item = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode first = deque.pollFirst();
                item.add(first.val);
                if(first.left != null) {
                    deque.addLast(first.left);
                }
                if(first.right != null) {
                    deque.addLast(first.right);
                }
            }
            ans.add(item);
        }
    }
}
